package com.blockmeta.bbs.overallserviceapplication.search.adapter;

import android.content.Context;
import android.content.Intent;
import androidx.annotation.Nullable;
import android.view.View;
import android.widget.ImageView;

import com.blockmeta.bbs.baselibrary.base.adapter.BaseAdapter;
import com.blockmeta.bbs.baselibrary.net.callback.MyStringCallback;
import com.blockmeta.bbs.baselibrary.utils.FormatUtil;
import com.blockmeta.bbs.baselibrary.utils.SharedPreferenceUtil;
import com.blockmeta.bbs.baselibrary.utils.ToastUtil;
import com.blockmeta.bbs.baselibrary.utils.loading.ProgressBarUtil;
import com.blockmeta.bbs.businesslibrary.constant.Constant;
import com.blockmeta.bbs.businesslibrary.constant.NetConstant;
import com.blockmeta.bbs.businesslibrary.eventbus.MsgSuccess;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.businesslibrary.util.ColorUtil;
import com.blockmeta.bbs.overallserviceapplication.R;
import com.blockmeta.bbs.overallserviceapplication.activity.login.LoginPhoneActivity;
import com.blockmeta.bbs.businesslibrary.pojo.SearchCoinsPOJO;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.zhy.http.okhttp.OkHttpUtils;

import org.greenrobot.eventbus.EventBus;

import java.util.HashMap;
import java.util.List;

import okhttp3.Call;
import okhttp3.MediaType;

/**
 * Created by author on 2018/1/30.
 */

public class CoinsSearchAdapter2 extends BaseAdapter<SearchCoinsPOJO.CoinsBean,BaseViewHolder> {
    public CoinsSearchAdapter2(int layoutResId, @Nullable List<SearchCoinsPOJO.CoinsBean> data) {
        super(layoutResId, data);
    }

    @Override
    protected void convert(BaseViewHolder helper, final SearchCoinsPOJO.CoinsBean item) {
        helper.setText(R.id.list_item_tv1, item.getName());
        helper.setText(R.id.list_item_tv2, item.getCoin().toUpperCase() + "/" + item.getCurrencyShow().toUpperCase());

        String volumn = FormatUtil.subString3(item.getTicker().getVolume());
        helper.setText(R.id.list_item_tv3, "交易量 " + " " + volumn + item.getCoin().toUpperCase());
        helper.setText(R.id.list_item_tv4, "¥ " + FormatUtil.usd2cny(item.getTicker().getLast(), item.getConvert_cny()));
        helper.setText(R.id.list_item_tv4_down, FormatUtil.getPriceStyle(item.getCurrency())+FormatUtil.notation2String(item.getTicker().getLast()));


        //科学技术发转String
        String blast = FormatUtil.notation2String(item.getTicker().getLast());
        String before = FormatUtil.notation2String(item.getTicker().getPrice_24h_before());
        //百分比计算
        double result = Double.parseDouble(blast) - Double.parseDouble(before);

        String format = FormatUtil.percentC(blast, before);
        if (result < 0) {
            helper.setBackgroundRes(R.id.list_item_tv5, ColorUtil.getDownsBg());
            helper.setText(R.id.list_item_tv5, format + "%");
        } else {
            helper.setBackgroundRes(R.id.list_item_tv5, ColorUtil.getUpsBg());
            helper.setText(R.id.list_item_tv5, "+" + format + "%");
        }

        ImageView view = helper.getView(R.id.iv_collection);
        view.setImageResource(item.isOptional()?R.drawable.icon_minus:R.drawable.icon_plus);
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (AccountHelper.isLogin()) {
                    if (item.isOptional()) {
                        //删除自选
                        postDeleteChoiceNet(item);
                    } else {
                        //添加自选
                        postAddChoiceNet(item);
                    }
                } else {
                    startActivityToLogin(mContext);
                }
            }
        });
    }
    /**
     * 删除自选
     */
    private void postDeleteChoiceNet(final SearchCoinsPOJO.CoinsBean coinsBean) {
        ProgressBarUtil.showProgress(mContext);
        String pair = coinsBean.getCoin().toLowerCase() + "_" + coinsBean.getCurrency().toLowerCase();
        String exchange = coinsBean.getExchange();
        OkHttpUtils.delete()
                .addHeader("from", "android")
                .addHeader("token", SharedPreferenceUtil.getString(mContext, Constant.TOKEN, ""))
                .addHeader("uid", AccountHelper.getUid())
                .url(NetConstant.MY_CHOICE + "?pair=" + pair + "&exchange=" + exchange)
                .build()
                .execute(new MyStringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ProgressBarUtil.dismissProgress(mContext);
                        ToastUtil.show(mContext,"联网失败，请检查网络");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ProgressBarUtil.dismissProgress(mContext);
                        coinsBean.setOptional(false);
                        notifyItemChanged(getData().indexOf(coinsBean));
                        EventBus.getDefault().postSticky(new MsgSuccess("UPDATECOLLECTION"));

                    }
                });
    }

    /**
     * 添加自选
     */
    private void postAddChoiceNet(final SearchCoinsPOJO.CoinsBean coinsBean) {
        ProgressBarUtil.showProgress(mContext);
        String pair = coinsBean.getCoin().toLowerCase() + "_" + coinsBean.getCurrency().toLowerCase();
        String exchange = coinsBean.getExchange();
        HashMap<String, String> map = new HashMap<>();
        map.put("pair", pair);
        map.put("exchange", exchange);
        OkHttpUtils.postString()
                .addHeader("from", "android")
                .addHeader("token", SharedPreferenceUtil.getString(mContext, Constant.TOKEN, ""))
                .addHeader("uid", AccountHelper.getUid())
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(new Gson().toJson(map))
                .url(NetConstant.MY_CHOICE)
                .build()
                .execute(new MyStringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ProgressBarUtil.dismissProgress(mContext);
                        ToastUtil.show(mContext,"联网失败，请检查网络");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        ProgressBarUtil.dismissProgress(mContext);
                        coinsBean.setOptional(true);
                        notifyItemChanged(getData().indexOf(coinsBean));
                        EventBus.getDefault().postSticky(new MsgSuccess("UPDATECOLLECTION"));

                    }
                });
    }

    /**
     * 跳到登陆页面
     *
     * @param context
     */
    public void startActivityToLogin(Context context) {
        Intent intent = new Intent(context, LoginPhoneActivity.class);
        context.startActivity(intent);
    }
}
